package com.kobeliu.netty.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 用于检测channel的心跳处理器
 * 继承ChannelInboundHandlerAdapter
 */
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if(evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent) evt;

            if(event.state() == IdleState.READER_IDLE){
                System.out.println("进入读空闲");
            }else if(event.state() == IdleState.WRITER_IDLE){
                System.out.println("进入写空闲");
            }else if(event.state() == IdleState.ALL_IDLE){
                System.out.println("全空闲");

                String longId = ctx.channel().id().asLongText();
                String userId = UserChannelSession.getUserId(longId);

                UserChannelSession.deleteChannelByUserId(userId,ctx.channel());
                UserChannelSession.removeLongIdAndUserId(longId,userId);

                ctx.channel().close();

            }

        }
    }

}
